﻿// <copyright file="ControlsHelper.cs" company="Embedded Media Framework">
// Published unter MS-PL at http://www.codeplex.com/emf
// Copyright (c) 2008 All Right Reserved
// </copyright>
// <author>Ulrich 'connex' Strauss</author>
// <email>http://www.codeplex.com/emf/</email>
// <date>2008-11-13</date>
// <summary>Contains helper functions for controls</summary>

using System;
using System.Drawing;

namespace EMF.Forms.Utils
{
    /// <summary>
    /// Helpers for Controls
    /// </summary>
    internal partial class ControlsHelper
    {
        /// <summary>
        /// Draws an (resized) image with alpha blending to the given Graphics context
        /// </summary>
        /// <param name="gx">The Graphics to draw to</param>
        /// <param name="image">The Bitmap to draw</param>
        /// <param name="alphaFactor">Alpha blending factor (0 = transparent , 0xff = opaque)</param>
        /// <param name="x">Target X-Postion</param>
        /// <param name="y">Target Y-Position</param>
        /// <param name="width">Target Width</param>
        /// <param name="height">Target Height</param>
        public static void DrawAlphaBlended(Graphics gx, Bitmap image, byte alphaFactor, int x, int y, int width, int height)
        {
            using (Graphics gxSrc = Graphics.FromImage(image))
            {
                IntPtr hdcDst = gx.GetHdc();
                IntPtr hdcSrc = gxSrc.GetHdc();
                BlendFunction blendFunction = new BlendFunction();
                blendFunction.BlendOp = (byte)BlendOperation.AC_SRC_OVER;   // Only supported blend operation
                blendFunction.BlendFlags = (byte)BlendFlags.Zero;           // Documentation says put 0 here
                blendFunction.SourceConstantAlpha = alphaFactor;            // Constant alpha factor
                blendFunction.AlphaFormat = (byte)0;                        // Don't look for per pixel alpha

                PlatformAPIs.AlphaBlend(hdcDst, x, y, width, height, hdcSrc, 0, 0, image.Width, image.Height, blendFunction);

                gx.ReleaseHdc(hdcDst);                                      // Required cleanup to GetHdc()
                gxSrc.ReleaseHdc(hdcSrc);                                   // Required cleanup to GetHdc()
            }
        }
    }
}
